#include "../Log/nhylog.hpp"

#include <iostream>
#include <vector>
#include <thread>
#include <chrono>

void bench(const std::string &logger_name, size_t thr_count, size_t msg_count, size_t msg_len)
{
    nhylog::Logger::ptr logger = nhylog::getLogger(logger_name);
    if (logger.get() == nullptr) return;
    std::cout << "测试日志：" << msg_count << "条，总大小:" << msg_count * msg_len / 1024 << "kb" << std::endl;
    std::string msg(msg_len - 1, 'A'); 
    msg.append("/n");
    std::vector<std::thread> threads;
    std::vector<double> cost_array(thr_count);
    size_t msg_per_thread = msg_count / thr_count; // 每个线程要输出的日志数量
    for (int i = 0; i < thr_count; i++)
    {
        threads.emplace_back([&, i]{
            auto start = std::chrono::high_resolution_clock::now();
            for (int j = 0; j < msg_per_thread; j++){
                logger->fatal("%s", msg.c_str());
            }
            auto end = std::chrono::high_resolution_clock::now();
            std::chrono::duration<double> cost = end - start;
            cost_array[i] = cost.count();
            std::cout << "thread" << i << ":"
                    << "\t输出日志数量:"
                    << msg_per_thread << "\t共耗时 :" << cost.count() << "s" << std::endl;
        });
    }

    for (int i = 0; i < thr_count; i++)
    {
        threads[i].join();
    }
    double max_cost = cost_array[0];
    for (int i = 0; i < thr_count; i++){
        max_cost = std::max(max_cost, cost_array[i]);
    }
    size_t msg_per_sec = msg_count / max_cost;
    size_t size_per_sec = (msg_count * msg_len) / (max_cost * 1024);
    std::cout << "每秒输出数量：" << msg_per_sec << "条" << std::endl;
    std::cout << "每秒输出大小：" << size_per_sec << "kb" << std::endl;
    std::cout << std::endl;
}

void sync_bench()
{
    std::unique_ptr<nhylog::LoggerBuilder> builder(new nhylog::GlobalLoggerBuilder());
    //指挥者的目的是让对象的各个零件按照一定顺序去构造，这里不需要顺序，因此不需要指挥者类
    builder->buildLoggerName("sync_logger");
    builder->buildFormatter("%m%n");
    builder->buildLoggerType(nhylog::LoggerType::LOGGER_SYNC);
    builder->buildSink<nhylog::FileSink>("./logfile/sync.log");
    builder->build();

    bench("sync_logger",1,1000000,100);
}

void async_bench()
{
    std::unique_ptr<nhylog::LoggerBuilder> builder(new nhylog::GlobalLoggerBuilder());
    //指挥者的目的是让对象的各个零件按照一定顺序去构造，这里不需要顺序，因此不需要指挥者类


    builder->buildLoggerName("async_logger");
    builder->buildFormatter("%m%n");
    builder->buildLoggerType(nhylog::LoggerType::LOGGER_ASYNC);
    builder->buildLooperType(nhylog::AsyncType::ASYNC_UNSAFE);
    builder->buildSink<nhylog::FileSink>("./logfile/sync.log");
    builder->build();

    bench("async_logger",1,1000000,100);
}

int main()
{


    return 0;
}
